package com.whz.gateway.configure.access.rules.black;

import com.whz.gateway.common.GatewayMessageAccessor;
import com.whz.gateway.common.constants.GatewayConstant;
import com.whz.gateway.common.util.GatewayIpUtils;
import com.whz.gateway.common.util.PathMatcherUtils;
import com.whz.gateway.limit.IBlackRule;
import com.whz.generic.utils.IpUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;

/**
 * 非内网访问的swagger路径,禁止访问
 *
 * @author whz
 */
@Component
public class SwaggerForbiddenRule implements IBlackRule {
    @Override
    public String getName() {
        return "SwaggerForbiddenRule";
    }

    @Override
    public String getMessage() {
        return GatewayMessageAccessor.getMessage(
                "gateway.config.rules.black.SwaggerForbiddenRule.URL_FORBIDDEN");
    }

    @Override
    public boolean test(ServerWebExchange exchange) {
        return Arrays.stream(GatewayConstant.SWAGGER_BLACK_LIST_PATHS).anyMatch(
                path -> PathMatcherUtils.match(path, exchange.getRequest().getPath().value()) &&
                        !IpUtils.isInnerIp(GatewayIpUtils.getRemoteIp(exchange.getRequest())));
    }
}